import { createRouter, createWebHashHistory } from "vue-router";
import HomePage from "@/views/Home/HomePage";
import LoginPage from "@/views/login/LoginPage";
import store from "@/store";
const GoodsDetailPage = () => import("@/views/goods/GoodsDetailPage");
const OneCategory = () => import("@/views/category/OneCategory");
const TwoCategory = () => import("@/views/category/TwoCategory");
const LoginCallbackPage = () =>
  import("@/views/login/components/LoginCallbackPage");
const CartPage = () => import("@/views/cart/cartPage");
const CheckoutPage = () => import("@/views/pay/CheckoutPage");
const PayPage = () => import("@/views/pay/PayPage");
const PayResultPage = () => import("@/views/pay/PayResultPage");
const MemberHomePage = () => import("@/views/member/home/MemberHomePage");
const OrderListPage = () => import("@/views/member/order/OrderListPage");
const OrderDetailPage = () => import("@/views/member/order/OrderDetailPage");
const OrderView = () => import("@/views/member/order/OrderView");
const routes = [
  {
    path: "/",
    component: HomePage,
  },
  {
    path: "/category/:id",
    component: OneCategory,
  },
  {
    path: "/category/sub/:id",
    component: TwoCategory,
  },
  {
    path: "/goods/:id",
    component: GoodsDetailPage,
  },
  {
    path: "/login",
    component: LoginPage,
  },
  {
    path: "/login/callback",
    component: LoginCallbackPage,
  },
  {
    path: "/cart",
    component: CartPage,
  },
  {
    path: "/checkout/order",
    component: CheckoutPage,
  },
  {
    path: "/checkout/pay",
    component: PayPage,
  },
  {
    path: "/pay/callback",
    component: PayResultPage,
  },
  {
    path: "/member/home",
    component: MemberHomePage,
  },
  {
    path: "/member/order",
    component: OrderView,
    children: [
      {
        path: "",
        component: OrderListPage,
      },
      {
        path: ":id",
        component: OrderDetailPage,
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  // 路由跳转时回到顶部
  scrollBehavior: () => ({ top: 0 }),
  linkActiveClass: "fuzzy-active",
  linkExactActiveClass: "exact-active",
  routes,
});

router.beforeEach((to, form, next) => {
  // 规定 路由地址已checkout，member开头的都需要登录
  const requiredLogin = ["checkout", "member"];
  if (requiredLogin.includes(to.path.split("/")[1])) {
    // 如果用户没有登录
    if (!store.state.user.profile.token) {
      next({ path: "/login", query: { redirectURL: to.fullPath } });
    } else {
      // 如果用户登录了
      next();
    }
  } else {
    next();
  }
});

export default router;
